package com.wang.util;

import com.wang.auto.addSet.AddSetAutoSend;
import com.wang.conf.AppConf;
import com.wang.conf.AppData;
import com.wang.conf.DevManager;
import com.wang.packpojo.AddSetMsg;
import com.wang.packpojo.ConMsg;
import com.wang.pojo.*;
import com.wang.service.*;
import com.wang.socket.OutBoundHandler;
import com.wang.socket.SocketMap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author wcy
 * @date 2023-07-18 15:46
 */
@Component
public class DevControlUtil {

    //用于处理接收指令数据处理

    //通用性
    public static void handerControl1(ByteBuf in, String devGId,Integer mCountNum){

        //重置读取位
        in.resetReaderIndex();
        //读取八位数据
        int reablesLength = in.readableBytes();

        //至少5位
        if(reablesLength>=5 && mCountNum <= 3){
            for(int i =5;i<=reablesLength;i++) {

                byte[] bytes = new byte[i];
                in.readBytes(bytes);
                String baseData = ModBusUtil.bytes2HexString(bytes);
                String[] baseDatas = baseData.split(" ");
                String crc = baseDatas[baseDatas.length-2] + baseDatas[baseDatas.length-1];

                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < baseDatas.length-2; j++) {
                    sb.append(baseDatas[j]);
                }
                String data = sb.toString();

                byte[] bytes1 = ModBusUtil.HexString2Bytes(data);
                String sbCrc = ModBusUtil.getCRC3(bytes1);


                if(sbCrc.equals(crc)){


                    //开始校验整个数据
                    if(AppData.returnMap.containsKey(devGId)){

                        //获取发送信息
                        Map<String,Object> map = new HashMap<>();
                        map = AppData.returnMap.get(devGId);
                        if(map.size()>0) {

                            synchronized (map) {

                            for (Map.Entry<String, Object> entry : map.entrySet()) {

                                DevMControlService devMControlService = SpringUtil.getBean("devMControlServiceImpl", DevMControlServiceImpl.class);
                                Integer controlId = Integer.parseInt(entry.getKey());


                                DevMControl devMControl = devMControlService.selectDevControlById(controlId);
                                if (devMControl != null) {



                                    //查询
                                    DevMControlReturnService devMControlReturnService = SpringUtil.getBean("devMControlReturnServiceImpl", DevMControlReturnServiceImpl.class);
                                    List<DevMControlReturn> devMControlReturnList = devMControlReturnService.selectDevMControlReturnByControlId(devMControl.getControlId());


                                    if (devMControlReturnList.size() > 0) {



                                        for (DevMControlReturn devMControlReturn : devMControlReturnList) {



                                            if (devMControlReturn.getControlReturnData().replaceAll(" ", "").equals(baseData.replaceAll(" ", ""))) {
                                                //放置回复的数据
                                                AppData.returnMap.get(devGId).put(devMControl.getControlId().toString(), devMControlReturn.getControlReturnData());


                                                in.discardReadBytes();

                                                //进行更新状态
                                                //通用处理1
                                                System.out.println("进入状态更新1");

                                                DevControlFunService devControlFunService = SpringUtil.getBean("devControlFunServiceImpl", DevControlFunServiceImpl.class);
                                                Integer nowStatus = 0;

                                                mCountNum = 0;

                                                DeviceService deviceService = SpringUtil.getBean("deviceServiceImpl",DeviceServiceImpl.class);
                                                Device device = deviceService.selectDeviceByDevGId(devGId);
                                                DevLogService devLogService = SpringUtil.getBean("devLogServiceImpl",DevLogServiceImpl.class);
                                                UserService userService = SpringUtil.getBean("userServiceImpl",UserServiceImpl.class);
                                                User user = userService.selectUserByUserId(device.getUserId());


                                                switch (devMControl.getMakeProperty()) {

                                                    case "read":
                                                        //更新数据库控制状态

                                                        switch (devMControlReturn.getMakeProperty()) {

                                                            case "open": //开启状态
                                                                nowStatus = 1;
                                                                devControlFunService.updateDevControlFunNowStatus(devMControl.getFunId(), nowStatus);

                                                                break;
                                                            case "close": //关闭状态
                                                                nowStatus = 0;
                                                                devControlFunService.updateDevControlFunNowStatus(devMControl.getFunId(), nowStatus);
                                                                break;
                                                            default:
                                                                break;
                                                        }

                                                        AppData.returnMap.get(devGId).remove(devMControl.getControlId().toString());
                                                        break;
                                                    case "close":
                                                        nowStatus = 0;
                                                        devControlFunService.updateDevControlFunNowStatus(devMControl.getFunId(), nowStatus);


                                                        //记录日志
                                                        DevLog devLog = new DevLog();
                                                        devLog.setDevLogTypeCode("0059");
                                                        devLog.setDevEventTypeCode("0141");
                                                        devLog.setDevLogContent(devMControlReturn.getControlReturnName());
                                                        devLog.setCreateTime(DateUtil.getStrDate());
                                                        devLog.setDevId(device.getDevId().toString());
                                                        devLog.setIsRead(1);
                                                        if(user!=null){
                                                            devLog.setOperateUser(user.getUserNearName());
                                                        }
                                                        devLogService.addDevLog(devLog);

                                                        break;

                                                    case "open":
                                                        nowStatus = 1;
                                                        devControlFunService.updateDevControlFunNowStatus(devMControl.getFunId(), nowStatus);

                                                        //记录日志
                                                        DevLog devLog1 = new DevLog();
                                                        devLog1.setDevLogTypeCode("0059");
                                                        devLog1.setDevEventTypeCode("0141");
                                                        devLog1.setDevLogContent(devMControlReturn.getControlReturnName());
                                                        devLog1.setCreateTime(DateUtil.getStrDate());
                                                        devLog1.setDevId(device.getDevId().toString());
                                                        devLog1.setIsRead(1);
                                                        if(user!=null){
                                                            devLog1.setOperateUser(user.getUserNearName());
                                                        }
                                                        devLogService.addDevLog(devLog1);
                                                       /* //单独处理  在打开的地方 切换检测参数 设备已删除
                                                        if(devGId.equals("LH-DZ_93Y48620F") ){

                                                            handerChangeDevCheckParam(devMControl.getFunId(),nowStatus);
                                                        }
*/


                                                        break;
                                                    default:
                                                        break;

                                                }
                                                break;
                                            }
                                        }
                                    }
                                }


                            }};
                        }



                    }else {
                        in.clear();
                    }

                    //跳出循环
                    in.discardReadBytes();
                    break;
                }else {
                    in.resetReaderIndex();
                }

            }

        }else {
            in.clear();
        }


    }
    //功能码10 单独处理  目前先作为电极校准处理
    public static void handerControl2(ByteBuf in, String devGId,Integer mCountNum){

        //重置读取位
        in.resetReaderIndex();
        //读取八位数据
        int reablesLength = in.readableBytes();

        //至少5位

        if(reablesLength>=5 && mCountNum <= 3){

            for(int i =5;i<=reablesLength;i++) {

                byte[] bytes = new byte[i];
                in.readBytes(bytes);
                String baseData = ModBusUtil.bytes2HexString(bytes);
                String[] baseDatas = baseData.split(" ");
                String crc = baseDatas[baseDatas.length-2] + baseDatas[baseDatas.length-1];

                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < baseDatas.length-2; j++) {
                    sb.append(baseDatas[j]);
                }
                String data = sb.toString();

                byte[] bytes1 = ModBusUtil.HexString2Bytes(data);
                String sbCrc = ModBusUtil.getCRC3(bytes1);

                if(sbCrc.equals(crc)){
                    //开始校验整个数据
                    if(AppData.returnMap.containsKey(devGId)){

                        //获取发送信息
                        Map<String,Object> map = new HashMap<>();
                        map = AppData.returnMap.get(devGId);
                        if(map.size()>0) {

                            synchronized (map) {

                            for (Map.Entry<String, Object> entry : map.entrySet()) {

                                CalibrationControlService calibrationControlService  = SpringUtil.getBean("calibrationControlServiceImpl", CalibrationControlServiceImpl.class);

                                Integer controlId = Integer.parseInt(entry.getKey());


                                CalibrationControl calibrationControl = calibrationControlService.getById(controlId);
                                if (calibrationControl != null) {

                                    //查询
                                    CalibrationReturnService calibrationReturnService = SpringUtil.getBean("calibrationReturnServiceImpl", CalibrationReturnServiceImpl.class);
                                    CalibrationReturn calibrationReturn = calibrationReturnService.selectByControlId(calibrationControl.getControlId());

                                    if (calibrationReturn !=null ) {

                                            if (calibrationReturn.getControlReturnData().replaceAll(" ", "").equals(baseData.replaceAll(" ", ""))) {
                                                //放置回复的数据
                                                AppData.returnMap.get(devGId).put(calibrationControl.getControlId().toString(), calibrationReturn.getControlReturnData());
                                                //回收已读字节
                                                in.discardReadBytes();

                                                //进行更新状态
                                                //通用处理1
                                                System.out.println("进入状态更新1");
                                                mCountNum = 0;
                                            }

                                    }
                                }


                            }};
                        }



                    }else {
                        in.clear();
                    }

                    //跳出循环
                    in.discardReadBytes();
                    break;
                }else {
                    in.resetReaderIndex();
                }

            }

        }else {
            in.clear();
        }


    }

    //付红航定制功能
    public static void handlerControl3(ByteBuf in, String devGId,Integer mCountNum){

        //重置读取位
        in.resetReaderIndex();
        //读取八位数据
        int reablesLength = in.readableBytes();
        //至少5位

        if(reablesLength>=5 && mCountNum <= 3){


            for(int i =5;i<=reablesLength;i++) {
                byte[] bytes = new byte[0];
                try {
                    bytes = new byte[i];
                } catch (Exception e) {
                    e.printStackTrace();
                }
                in.readBytes(bytes);
                String baseData = ModBusUtil.bytes2HexString(bytes);
                String[] baseDatas = baseData.split(" ");
                String crc = baseDatas[baseDatas.length - 2] + baseDatas[baseDatas.length - 1];

                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < baseDatas.length - 2; j++) {
                    sb.append(baseDatas[j]);
                }
                String data = sb.toString();

                byte[] bytes1 = ModBusUtil.HexString2Bytes(data);
                String sbCrc = ModBusUtil.getCRC3(bytes1);

                if (sbCrc.equals(crc)) {
                    //开始校验整个数据
                    if (AppData.returnMap.containsKey(devGId)) {

                        //获取发送信息
                        Map<String, Object> map = new HashMap<>();
                        map = AppData.returnMap.get(devGId);
                        if (map.size() > 0) {

                            synchronized (map) {

                                for (Map.Entry<String, Object> entry : map.entrySet()) {

                                    Custom2ControlService custom2ControlService = SpringUtil.getBean("custom2ControlServiceImpl", Custom2ControlServiceImpl.class);

                                    Integer controlId = Integer.parseInt(entry.getKey());


                                    Custom2Control custom2Control = custom2ControlService.getById(controlId);
                                    if (custom2Control != null) {

                                            //查询
                                            Custom2ReturnService custom2ReturnService = SpringUtil.getBean("custom2ReturnServiceImpl", Custom2ReturnServiceImpl.class);
                                            List<Custom2Return> custom2ReturnList = custom2ReturnService.selectListByControlId(custom2Control.getControlId());
                                            if (custom2ReturnList.size() > 0) {
                                                for (Custom2Return custom2Return : custom2ReturnList) {
                                                    if (custom2Return.getControlReturnData().replaceAll(" ", "").equals(baseData.replaceAll(" ", ""))) {
                                                        //放置回复的数据
                                                        AppData.returnMap.get(devGId).put(custom2Control.getControlId().toString(), custom2Return.getControlReturnData());
                                                        //回收已读字节
                                                        in.discardReadBytes();


                                                        //进行更新状态
                                                        //通用处理1
                                                        System.out.println("进入状态更新1");
                                                        mCountNum = 0;
                                                        break;
                                                    }
                                                }


                                            }

                                    }
                                }
                                ;
                            }


                        } else {
                            in.clear();
                        }

                        //跳出循环
                        in.discardReadBytes();
                        break;
                    } else {
                        in.resetReaderIndex();
                    }

                }else {
                    in.resetReaderIndex();
                }
            }

        }else {
            in.clear();
        }
    }

    //切换设备检测参数  //单个设备定制使用 已停用
 /*   public static void handerChangeDevCheckParam(Integer funId,Integer nowStatus){



        String changeDevGId = "LH-DZ_313AX3788";

        DeviceService deviceService = SpringUtil.getBean("deviceServiceImpl",DeviceServiceImpl.class);
        Device device  = deviceService.selectDeviceByDevGId(changeDevGId);

        DevMdtParamConfDataService devMdtParamConfDataService = SpringUtil.getBean("devMdtParamConfDataServiceImpl",DevMdtParamConfDataServiceImpl.class);

        String yuCodCode = "0229";
        String yuAndanCode = "0230";
        String wuCodCode = "0231";
        String wuAndanCode = "0232";



        //查询modbus 检测参数
        switch (funId){
            case 1 :
                //雨水控制
                if(nowStatus.equals(1)){
                    //把设备的参数检测改为雨水参数

                    DevMdtParamConfData devMdtParamConfData1 = devMdtParamConfDataService.selectDevMdtParamConfDataByDevIdAndParamCode(device.getDevId(),wuCodCode);
                    if(devMdtParamConfData1 !=null){
                        //更改检测参数  污水cod 更换为雨水cod
                        devMdtParamConfDataService.editCheckParamCodeById(devMdtParamConfData1.getConfDataId(),yuCodCode);
                    }
                    DevMdtParamConfData devMdtParamConfData2 = devMdtParamConfDataService.selectDevMdtParamConfDataByDevIdAndParamCode(device.getDevId(),wuAndanCode);
                    if(devMdtParamConfData2 !=null){
                        //更改检测参数  污水氨氮 更换为雨水氨氮
                        devMdtParamConfDataService.editCheckParamCodeById(devMdtParamConfData2.getConfDataId(),yuAndanCode);
                    }

                    //更新全局变量参数
                    PrintUtil.print("设备："+changeDevGId+":由污水切换成雨水");
                    DevManager.updateDevDate(changeDevGId);
                    //记录日志
                    DevLog devLog = new DevLog();
                    devLog.setDevLogTypeCode("0059");
                    devLog.setDevEventTypeCode("0141");
                    devLog.setDevLogContent("污水切换成雨水");
                    devLog.setCreateTime(DateUtil.getStrDate());
                    devLog.setDevId(device.getDevId().toString());
                    devLog.setIsRead(1);
                    DevLogService devLogService = SpringUtil.getBean("devLogServiceImpl",DevLogServiceImpl.class);
                    devLogService.addDevLog(devLog);
                }
                break;
            case 2 :
                if(nowStatus.equals(1)){
                    //把设备的参数检测改为污水参数

                    DevMdtParamConfData devMdtParamConfData3 = devMdtParamConfDataService.selectDevMdtParamConfDataByDevIdAndParamCode(device.getDevId(),yuCodCode);
                    if(devMdtParamConfData3 !=null){
                        //更改检测参数  雨水cod 更换为污水cod
                        devMdtParamConfDataService.editCheckParamCodeById(devMdtParamConfData3.getConfDataId(),wuCodCode);
                    }
                    DevMdtParamConfData devMdtParamConfData4 = devMdtParamConfDataService.selectDevMdtParamConfDataByDevIdAndParamCode(device.getDevId(),yuAndanCode);
                    if(devMdtParamConfData4 !=null){
                        //更改检测参数  雨水氨氮 更换为污水氨氮
                        devMdtParamConfDataService.editCheckParamCodeById(devMdtParamConfData4.getConfDataId(),wuAndanCode);
                    }
                    //更新全局变量参数
                    PrintUtil.print("设备："+changeDevGId+":由雨水切换成污水");

                    DevManager.updateDevDate(changeDevGId);
                    //记录日志
                    DevLog devLog = new DevLog();
                    devLog.setDevLogTypeCode("0059");
                    devLog.setDevEventTypeCode("0141");
                    devLog.setDevLogContent("雨水切换成污水");
                    devLog.setCreateTime(DateUtil.getStrDate());
                    devLog.setDevId(device.getDevId().toString());
                    devLog.setIsRead(1);
                    DevLogService devLogService = SpringUtil.getBean("devLogServiceImpl",DevLogServiceImpl.class);
                    devLogService.addDevLog(devLog);
                }
                break;
            default:
                break;
        }

        //更新设备发送指令时间   初始化发送时间
        for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(changeDevGId)) {
                entry.getValue().setSendCommandTime(new Date().getTime());
            }

        }


    }*/



    //针对设备LH-DZ_93Y48620F  开机 进行校准状态
    public static void correctSwitchStatus(ChannelHandlerContext ctx,String devGId) throws UnsupportedEncodingException {


        new Thread(()->{

            try {
                Thread.sleep(1000*10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //1、查询数据库中目前的状态
            DeviceService deviceService = SpringUtil.getBean("deviceServiceImpl",DeviceServiceImpl.class);
            Device  device = deviceService.selectDeviceByDevGId(devGId);
            DevControlFunService devControlFunService = SpringUtil.getBean("devControlFunServiceImpl",DevControlFunServiceImpl.class);
            List<DevControlFun> devControlFunList = devControlFunService.selectDevControlFunByDevId(device.getDevId());


            //2、修改状态
            for(DevControlFun devControlFun : devControlFunList){
                //开启状态
                if(devControlFun.getNowStatus().equals(1)){
                    //打开
                    //查询开启指令
                    DevMControlService devMControlService = SpringUtil.getBean("devMControlServiceImpl",DevMControlServiceImpl.class);
                    String makeProperty = "open";
                    DevMControl devMControl = devMControlService.selectDevControlByVo(devControlFun.getFunId(), makeProperty);
                    //执行该命令
                    PrintUtil.print(devGId+"开机校准1："+devMControl.getControlData());
                    byte[] commandByte = ModBusUtil.HexString2Bytes(devMControl.getControlData());
                    OutBoundHandler.outData(ctx,commandByte);

                }else {
                    //打开
                    //查询开启指令
                    DevMControlService devMControlService = SpringUtil.getBean("devMControlServiceImpl",DevMControlServiceImpl.class);
                    String makeProperty = "close";

                    DevMControl devMControl = devMControlService.selectDevControlByVo(devControlFun.getFunId(), makeProperty);
                    //执行该命令

                    PrintUtil.print(devGId+"开机校准2："+devMControl.getControlData());
                    byte[] commandByte = ModBusUtil.HexString2Bytes(devMControl.getControlData());
                    OutBoundHandler.outData(ctx,commandByte);
                }

                try {
                    Thread.sleep(2500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    //针对设备LH-DZ_98S343C95   设备开机 空调默认设置启动
    public static void setStartStatus(String devGId) {

        DeviceService deviceService = SpringUtil.getBean("deviceServiceImpl",DeviceServiceImpl.class);
        Device  device = deviceService.selectDeviceByDevGId(devGId);
        DevControlFunService devControlFunService = SpringUtil.getBean("devControlFunServiceImpl",DevControlFunServiceImpl.class);
        List<DevControlFun> devControlFunList = devControlFunService.selectDevControlFunByDevId(device.getDevId());

        DevControlFun devControlFun = devControlFunList.get(0);

        //设置空调开关为开的状态
        Integer nowStatus = 1;
        devControlFunService.updateDevControlFunNowStatus(devControlFun.getFunId(),nowStatus);


    }
}
